package com.party.jackclientandroid.ui_mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.party.jackclientandroid.Constant;
import com.party.jackclientandroid.adapter.MyCommonAdapter;
import com.party.jackclientandroid.api.CouponService;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.BaseActivityTitle;
import com.party.jackclientandroid.R;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.MyCouponPackage;
import com.party.jackclientandroid.loadviewhelper.help.OnLoadViewListener;
import com.party.jackclientandroid.loadviewhelper.load.LoadViewHelper;
import com.party.jackclientandroid.ui_home.activity.DiscountPayBillActivity;
import com.party.jackclientandroid.ui_home.activity.GroupBuyCouponDetailActivity;
import com.party.jackclientandroid.ui_home.activity.ReplaceMoneyCouponDetailActivity;
import com.party.jackclientandroid.ui_home.activity.SecondKillCouponDetailActivity;
import com.party.jackclientandroid.ui_home.activity.SpellingGroupCouponDetailActivity;
import com.party.jackclientandroid.ui_order.WatchCouponQRCodeActivity2;
import com.party.jackclientandroid.utils.ConstUtils;
import com.party.jackclientandroid.utils.TimeUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.functions.Consumer;

public class MyCouponPackageActivity extends BaseActivityTitle {

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refresh_layout;
    @BindView(R.id.recycler_view)
    RecyclerView recycler_view;

    private int page = 1;
    private CouponService couponService;
    private List<MyCouponPackage> dataList = new ArrayList<>();
    private MyCommonAdapter<MyCouponPackage> commonAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_coupon_package);
        initData();
    }

    protected void initData() {
        setMiddleText("我的券包");
        couponService = new CouponService(this);
        initView();
        helper = new LoadViewHelper(refresh_layout);
        helper.setListener(new OnLoadViewListener() {
            @Override
            public void onRetryClick() {
                loadData();
            }
        });
        helper.showLoading();
        loadData();
    }

    public void initView() {

        refresh_layout.setEnableFooterFollowWhenLoadFinished(true);
        commonAdapter = new MyCommonAdapter<MyCouponPackage>(mActivity, R.layout.item_my_coupon_package, dataList) {
            @Override
            protected void convert(ViewHolder viewHolder, final MyCouponPackage item, int position) {
                mApplication.getImageLoaderFactory().loadCommonImgByUrl(mActivity, item.getImgUrl(), (ImageView) viewHolder.getView(R.id.coupon_image_iv));
                viewHolder.setText(R.id.goods_type_name_tv, getGoodsTypeNameById(item.getType()));
                viewHolder.setText(R.id.coupon_title_tv, item.getItemName());
                viewHolder.setText(R.id.shop_name_tv, item.getShopName());

                viewHolder.setText(R.id.valid_date_tv, "仅限" + TimeUtil.timeStamp2Date(item.getDateStart() + "", "yyyy-MM-dd") +
                        "至" + TimeUtil.timeStamp2Date(item.getDateEnd() + "", "yyyy-MM-dd") + "使用");

                viewHolder.setText(R.id.valid_time_tv, "仅限" + TimeUtil.timeStamp2Time(item.getTimeStart()) +
                        "至" + TimeUtil.timeStamp2Time(item.getTimeEnd()) + "使用");


                viewHolder.setOnClickListener(R.id.use_btn, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (item.getType() == Constant.GOODS_TYPE_SECOND_KILL || item.getType() == Constant.GOODS_TYPE_REPLACE_MONEY) {
                                    Intent intent = new Intent(mActivity, DiscountPayBillActivity.class);
                                    intent.putExtra("shopId", item.getShopId() + "");
                                    intent.putExtra("couponId", item.getItemId() + "");
                                    startActivity(intent);
                                } else if (item.getType() == Constant.GOODS_TYPE_SPELLING_GROUP || item.getType() == Constant.GOODS_TYPE_GROUP_BUY) {
                                    Intent intent = new Intent(mActivity, WatchCouponQRCodeActivity2.class);
                                    JSONObject jsonObject = new JSONObject();
                                    try {
                                        jsonObject.put("orderCode", item.getOrderCode());
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    intent.putExtra("orderCode", jsonObject.toString());
                                    startActivity(intent);
                                }
                            }
                        }
                );
            }
        };
        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                switch (dataList.get(position).getType()) {
                    //套餐券（团购券）
                    case Constant.GOODS_TYPE_GROUP_BUY:
                        Intent intent = new Intent(mActivity, GroupBuyCouponDetailActivity.class);
                        intent.putExtra("couponId", dataList.get(position).getItemId());
                        startActivity(intent);
                        break;
                    //代金券详情
                    case Constant.GOODS_TYPE_REPLACE_MONEY:
                        Intent intent2 = new Intent(mActivity, ReplaceMoneyCouponDetailActivity.class);
                        intent2.putExtra("couponId", dataList.get(position).getItemId());
                        startActivity(intent2);
                        break;
                    //秒杀券详情
                    case Constant.GOODS_TYPE_SECOND_KILL:
                        Intent intent3 = new Intent(mActivity, SecondKillCouponDetailActivity.class);
                        intent3.putExtra("couponId", dataList.get(position).getItemId());
                        startActivity(intent3);
                        break;
                    case Constant.GOODS_TYPE_SPELLING_GROUP:
                        Intent intent4 = new Intent(mActivity, SpellingGroupCouponDetailActivity.class);
                        intent4.putExtra("couponId", dataList.get(position).getItemId());
                        startActivity(intent4);
                        break;
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        refresh_layout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMoreData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                loadData();
            }
        });
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.layout_divider_item_decoration));
        recycler_view.addItemDecoration(divider);
        recycler_view.setLayoutManager(new LinearLayoutManager(mActivity));
        recycler_view.setAdapter(commonAdapter);
    }

    public void loadData() {
        page = 1;
        getNeedData();
    }

    public void getNeedData() {
        addDisposableIoMain(couponService.getMyCoupons(page, Constant.PAGE_SIZE), new DefaultConsumer<List<MyCouponPackage>>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<List<MyCouponPackage>> baseBean) {
                commonAdapter.clear(page);
                commonAdapter.addData(baseBean.getData());
                commonAdapter.finishLoading(page, page, baseBean.getData().size(), refresh_layout);
                helper.check(commonAdapter.getDatas());
            }
        });
    }

    public void loadMoreData() {
        page++;
        getNeedData();
    }

    public String getGoodsTypeNameById(int goodsType) {
        String goodsTypeName = null;
        switch (goodsType) {
            case Constant.GOODS_TYPE_GROUP_BUY:
                goodsTypeName = "(团购券)";
                break;
            case Constant.GOODS_TYPE_SPELLING_GROUP:
                goodsTypeName = "(拼团券)";
                break;
            case Constant.GOODS_TYPE_REPLACE_MONEY:
                goodsTypeName = "(代金券)";
                break;
            case Constant.GOODS_TYPE_SECOND_KILL:
                goodsTypeName = "(秒杀券)";
                break;
        }
        return goodsTypeName;
    }
}
